# -*- coding:utf-8 -*-
# File Name:ui_main.py
# Author:jing
# Date:2018/12/20
import traceback
from contextlib import redirect_stdout
from importlib import import_module
from io import StringIO
from tkinter import Tk, Menu, Text, END

from ui.tree_builder import TreeBuilder
from util.module_util import get_src
from util.ui_util import rewrite

__author__ = 'jing'


class Application(TreeBuilder):
    def refresh_content(self, *values):
        module = import_module(values[0])
        rewrite(self.content, get_src(module))

    def __init__(self, master: Tk = None):
        super().__init__(master)
        self.master = master
        self.master.bind_all('<Shift-Return>', self.commit)
        self.master.bind_all('<F10>', self.run)

        self.pack()

        bar = Menu(self)
        bar.add_command(label='commit [shift+enter]', command=self.commit)
        bar.add_command(label='run [F10]', command=self.run)

        self.show_tree = True
        self.master.config(menu=bar)

        self.tree = self.get_tree_view()
        self.tree.grid(row=0, column=0, sticky='nsew')

        self.content = Text(self, bg='gray22', fg='white', insertbackground='white', width=100, height=40)
        self.content.grid(row=0, column=1)

        self.console = Text(self, bg='gray22', fg='white', insertbackground='white', height=5)
        self.console.grid(row=1, column=0, columnspan=2, sticky='nsew')

    def commit(self, event=None):
        answer = self.console.get(1.0, END).strip()
        expect = self._get_result().strip()
        if answer == expect:
            rewrite(self.content, 'hhh')
        else:
            rewrite(self.content, 'error {} {}'.format(answer, expect))

    def run(self, evnet=None):
        rewrite(self.console, self._get_result())

    def _get_result(self):
        with StringIO() as s, redirect_stdout(s):
            try:
                exec(self.content.get(1.0, END))
                result = s.getvalue()
                return result
            except:
                return traceback.format_exc()
